<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="addRoleDialog()">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-row>
        <template>
          <el-table :data="roleList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row
                  :class="['vcenter',i1==0?'bdbottom':'',i1==0?'bdtop':'']"
                  v-for="(item1,i1) in scope.row.children"
                  :key="item1.id"
                >
                  <!-- 渲染一级权限 -->
                  <el-col :span="7">
                    <el-tag closable @close="deletetag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染二级和三级权限 -->
                  <el-col :span="17">
                    <el-row
                      :class="['vcenter',i2==0?'':'bdtop']"
                      v-for="(item2,i2) in item1.children"
                      :key="item2.id"
                    >
                      <el-col :span="7">
                        <el-tag
                          type="success"
                          closable
                          @close="deletetag(scope.row,item2.id)"
                        >{{item2.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="17">
                        <el-tag
                          type="warning"
                          v-for="(item3) in item2.children"
                          :key="item3.id"
                          closable
                          @close="deletetag(scope.row,item3.id)"
                        >{{item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <!-- <pre>
                    {{scope.row}}
                </pre>-->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editRoleInfo(scope.row.id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteRole(scope.row.id)"
                >删除</el-button>
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-setting"
                  @click="setShowRightDialog(scope.row)"
                >分配</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-row>
    </el-card>
    <!-- 设置角色权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="emptydefKeys()"
    >
      <el-tree
        :data="rightsList"
        :props="treeRights"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色信息" :visible.sync="editroledialogVisible" width="30%">
      <el-form
        ref="editroleInfoFormRef"
        :model="roleInfoForm"
        label-width="80px"
        :rules="roleInfoFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleInfoForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleInfoForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditRoleFileds()">取 消</el-button>
        <el-button type="primary" @click="editRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoledialogVisible" width="50%">
      <el-form ref="addroleformRef" :model="addroleform" :rules="addroleRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addroleform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addroleform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetFields()">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
     
<script>
export default {
  data() {
    return {
      roleId: "",
      defKeys: [],
      setRightDialogVisible: false,
      rightsList: [],
      roleList: [],
      roleInfoForm: {},
      addroleform: {},
      editroledialogVisible: false,
      treeRights: {
        children: "children",
        label: "authName",
      },
      roleInfoFormRules: {
        roleName: [
          { required: true, message: "请输入登录名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入登录名称", trigger: "blur" },
        ],
      },
      addroleRules: {
        roleName: [
          { required: true, message: "请输入登录名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入登录名称", trigger: "blur" },
        ],
      },
      addRoledialogVisible: false,
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //   编辑权限
    async allotRights() {
      const arr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];

      const str = arr.join(",");
      console.log("str");
      console.log(str);
      //   发起网络请求 修改权限
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: str }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
    //   设置角色权限对话框
    async setShowRightDialog(role) {
      //   发起网络请求获取全部权限列表
      const { data: res } = await this.$http.get("rights/tree");

      if (res.meta.status !== 200) return;
      this.roleId = role.id;
      this.rightsList = res.data;

      this.getdefnodes(role, this.defKeys);
      console.log("-------");
      console.log(role);
      console.log(this.defKeys);
      this.setRightDialogVisible = true;
    },
    emptydefKeys() {
      this.defKeys = [];
    },
    // 定义递归函数获取当前角色所有三级节点ID 并把它放入 defKeys数组
    getdefnodes(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
        console.log(arr);
      }
      node.children.forEach((item) => {
        this.getdefnodes(item, arr);
      });
    },
    //   删除权限
    async deletetag(role, id) {
      const { data: res } = await this.$http.delete(
        "roles/" + role.id + "/rights/" + id
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success("删除权限成功");
      console.log(role);
      role.children = res.data;
    },
    //   编辑角色对话框
    async editRoleInfo(id) {
      this.editroledialogVisible = true;
      //   获取用户信息
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) return;

      this.roleInfoForm = res.data;
      console.log("here");
      //   console.log(res.data);
      console.log(this.roleInfoForm);
    },
    // 重置编辑角色表单
    resetEditRoleFileds() {
      this.$refs.editroleInfoFormRef.resetFields();
    },
    // 编辑角色信息
    editRole() {
      // 预校验
      this.$refs.editroleInfoFormRef.validate(async (valid) => {
        if (!valid) return;
        //发起网络请求 修改角色信息
        const { data: res } = await this.$http.put(
          "roles/" + this.roleInfoForm.roleId,
          {
            roleName: this.roleInfoForm.roleName,
            roleDesc: this.roleInfoForm.roleDesc,
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("修改角色失败！");
        this.editroledialogVisible = false;
        this.getRolesList();
        this.$refs.editroleInfoFormRef.resetFields();
      });
    },
    //   重置添加角色表单
    resetFields() {
      this.$refs.addroleformRef.resetFields();
    },
    //   删除角色
    async deleteRole(id) {
      // 发起网络请求删除数据
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) this.$message.error(res.meta.msg);
      //   成功
      this.$message.success(res.meta.msg);
      this.getRolesList();
    },
    //   添加角色
    addRole() {
      // 预校验
      this.$refs.addroleformRef.validate(async (valid) => {
        if (!valid) return;
        // 发起网络请求
        const { data: res } = await this.$http.post("roles", this.addroleform);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        // 成功
        this.$refs.addroleformRef.resetFields();
        this.addRoledialogVisible = false;
        this.getRolesList();
        this.$message.success(res.meta.msg);
      });
    },
    //   添加角色对话框
    addRoleDialog() {
      this.addRoledialogVisible = true;
    },
    // 获得角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色信息失败！");
      }
      this.roleList = res.data;
      console.log("rolelist");
      console.log(this.roleList);
    },
  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.bdtop {
  border-top: 1px solid rgb(245, 240, 240);
}
.bdbottom {
  border-bottom: 1px solid rgb(245, 240, 240);
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>